package com.deshan.websys.api.controller;

import java.util.List;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.deshan.websys.api.utils.CommonResult;
import com.deshan.websys.code.model.Blogroll;
import com.deshan.websys.code.model.vo.BlogrollVO;
import com.deshan.websys.code.service.BlogrollService;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import net.sf.cglib.beans.BeanCopier;

@Api(tags = "友情链接后台管理")
@RestController
@RequestMapping("/manage/blogroll")
@AllArgsConstructor
public class BlogrollController {

	private final BlogrollService blogrollService;

	private final static BeanCopier beanCopier = BeanCopier.create(BlogrollVO.class, Blogroll.class, false);

	@ApiOperation("创建和修改")
	@PostMapping("/save")
	public CommonResult saveBlogroll(@RequestBody @Validated BlogrollVO blogrollVO) {
		Blogroll blogroll = new Blogroll();
		beanCopier.copy(blogrollVO, blogroll, null);
		blogroll.setPageType(2);
		return blogrollService.saveOrUpdate(blogroll) ? CommonResult.success() : CommonResult.failed("保存失败");
	}

	@ApiOperation("删除")
	@DeleteMapping("/delete/{id}")
	public CommonResult deleteBlogroll(@PathVariable("id") String id) {
		if (StrUtil.isBlank(id)) {
			return CommonResult.success();
		}
		return blogrollService.removeById(id) ? CommonResult.success() : CommonResult.failed("删除失败");
	}

	@ApiOperation("批量删除")
	@DeleteMapping("/delete/{ids}")
	public CommonResult batchDeleteBlogroll(@PathVariable("ids") String[] ids) {
		if (ArrayUtil.isNotEmpty(ids)) {
			for (String id : ids) {
				deleteBlogroll(id);
			}
		}
		return CommonResult.success();
	}

	@ApiOperation("查询当前法人下的所有友情链接")
	@GetMapping("/list/{legalCode}")
	public CommonResult<List<Blogroll>> listBlogroll(@PathVariable("legalCode") String legalCode) {
		return CommonResult.success(
				blogrollService.list(Wrappers.lambdaQuery(Blogroll.class).eq(Blogroll::getLegalCode, legalCode)));
	}

	@ApiOperation("根据ID查询友情链接")
	@GetMapping("/getone")
	public CommonResult<Blogroll> getBlogroll(@RequestParam("id") String id) {
		return CommonResult.success(blogrollService.getById(id));
	}

}
